#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include "Log.hpp"
#include "Comm.hpp"

using namespace lyrics;

int main(int argc, char *argv[])
{
    if(argc!= 3)
    {
        std::cout << "Usage: " << argv[0] << " <server_ip> <server_port>" << std::endl;
        Die(USAGE_ERR);
    }
    std::string server_ip = argv[1];
    int server_port = atoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "create socket failed";
        Die(SOCK_ERR);
    }
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    //第一次连接的时候会自动绑定
    int n = connect(sockfd,CONV(&server),sizeof(server));
    if(n < 0)
    {
        LOG(LogLevel::WARNING) << "connect failed, try again";
        Die(CONN_ERR);
    }
    LOG(LogLevel::INFO) << "connect success";

    //连接成功进行通信
    std::string message;
    while(true)
    {
        std::cout << "input message: ";
        std::getline(std::cin,message);
        
        n =write(sockfd,message.c_str(),message.size());
        if(n < 0)
        {
            std::cout << "write error" << std::endl;
            break;
        }

        char inbuffer[1024];
        int m = read(sockfd,inbuffer,sizeof(inbuffer));
        if(m > 0)
        {
            inbuffer[m] =0;
            std::cout << inbuffer<< std::endl;
        }
    }
    return 0;
}